import { Button, Image, RichText, Text, View } from '@tarojs/components'
import './index.scss'
import '@/styles/common/goods-info.scss'
import classNames from 'classnames'
import {getSharePath, verifyUserLogin} from '@/utils/storage'
// import { APP_SYSTEM_INFO } from "@/config/config"
import { filterGoodsInfo } from "@/utils/filter"
import { addCart } from '@/api/userApi'
import { goodsShareImg } from '@/api/wximagesApi'
import { getPage, infoById } from '@/api/productApi'
import { getCommentPage } from '@/api/commentApi'
import { formatAmount, formatHtml, showMemberPrice } from "@/utils/utils"
import {
  toCalcOrderPage,
  toMemberOpenPage,
  toCommentGoodsPage,
  toUserLoginPage
} from '@/utils/page_router'
import vipImg from '@/assets/icon/vip.png'
import FyComponent from "@/components/common/goods"
import {
  GoodsNavbar,
  Loading,
  TitleOne,
  AvatarList,
  GoodsCarousel,
  GoodsOneList,
  ShareImage,
  CommentGoods,
  GoodsSelect,
  BuyRecord
} from "@/components/index"
import GoodsFoot from "@/components/goods/goods-foot"

// const { navBarHeight } = APP_SYSTEM_INFO
export default class Index extends FyComponent {
  // state: any
  // rolling: boolean
  // config: Config = {
  //   navigationStyle: 'custom'
  // }
  // static options = {
  //   addGlobalClass: true
  // }

  componentWillMount() {
    this.getGoodsInfo()
    this.getPage()
    this.getCommentPage()
  }

  //  分享小程序
  onShareAppMessage() {
    return { title: this.state.goodsInfo.name, path: getSharePath() }
  }

  //  页面滚动触发事件的处理函数
  onPageScroll({ scrollTop }) {
    const { opacity, nodeKey, nodeList } = this.state

    const num:any = (scrollTop / 200).toFixed(2)
    const number = num >= 1 ? 1 : num
    if (opacity !== number) {
      this.setState({
        opacity: number
      })
    }

    if (this.rolling) {
      return false
    }

    const list = nodeList.filter(i => (scrollTop >= i.top))
    const k = list.length - 1
    if (nodeKey !== k) {
      this.setState({
        nodeKey: k
      })
    }
  }

  //  获取节点位置
  // getNodeLocation() {
  //   const query = Taro.createSelectorQuery()
  //   const list:any = [
  //     { name: '商品', id: '#goods-info' },
  //     { name: '评价', id: '#goods-comment' },
  //     { name: '详情', id: '#goods-desc' },
  //     { name: '推荐', id: '#goods-hot' }
  //   ]
  //   list.map(i => {
  //     query.select(i.id).boundingClientRect(rect => {
  //       if (rect) {
  //         i.top = Math.ceil(rect.top - navBarHeight)
  //       }
  //     })
  //   })
  //
  //   query.exec(() => {
  //     this.setState({
  //       nodeList: list.filter(i => i.top)
  //     })
  //   })
  // }

  //  切换节点
  onSwitchNode(item, key) {
    this.rolling = true

    this.setState({
      nodeKey: key
    }, () => {
      wx.pageScrollTo({
        scrollTop: item.top,
        duration: 300
      })
    })

    setTimeout(() => {
      this.rolling = false
    }, 400)
  }

  //  分页获取商品
  getPage() {
    getPage({ page: 1, limit: 6 }).then(res => {
      this.setState({
        goodsList: res.data.list
      })
    })
  }

  //  获取商品详情
  getGoodsInfo() {
    const { params } = this.$router
    infoById(params.id).then(res => {
      const {data} = res
      data.timestamp = Number(new Date())
      this.setState({
        goodsInfo: filterGoodsInfo(data),
        comboList: data.skuDetail || [],
        goodsImages: data.images
      }, () => {
        this.setState({
          loadingStatus: false
        })
        setTimeout(() => {
          this.getNodeLocation()
        }, 200)
      })
    }).catch(err => {
      console.log(err)
      setTimeout(() => {
        wx.navigateBack()
      }, 800)
    })
  }

  //  分页获取评论
  getCommentPage() {
    const { id } = this.state
    getCommentPage({ page: 1, limit: 2, productId: id }).then(res => {
      this.setState({
        commentRes: res.data
      })
    })
  }

  //  是否显示分享图
  setOpenShareImg(bool) {
    if (bool) {
      verifyUserLogin({
        success: () => {
          this.getGoodsShareImage()
          this.setState({
            showShareImg: true
          })
        },
        fail: () => {
          toUserLoginPage()
        }
      })
    } else {
      this.setState({
        showShareImg: false
      })
    }
  }

  //  显示选择商品
  setShowSelect(bool) {
    this.setState({
      showSelect: bool
    })
  }

  //  显示选择商品
  setShowMore(bool) {
    this.setState({
      showMore: bool
    })
  }

  //  商品分享图
  getGoodsShareImage() {
    const { goodsInfo } = this.state
    goodsShareImg(goodsInfo).then(res => {
      this.setState({
        shareImg: res.data
      })
    })
  }

  //  确认选择商品
  onConfirm(type, info, number) {
    // console.log(type)
    if (type === 'cart') {
      addCart({ productId: info.productId, skuId: info.skuId, number }).then(() => {
        wx.showToast({ title: '添加成功' })
      })
    } else {
      toCalcOrderPage({ cartList: [{ id: info.productId, skuId: info.skuId, number }] })
    }
    this.setState({
      showSelect: false
    })
  }

  render() {
    const { opacity, nodeKey, nodeList, userInfo, goodsInfo, goodsList, showSelect, showShareImg, shareImg, commentRes, loadingStatus } = this.state
    const percent:any = (100 / nodeList.length).toFixed(2)
    return (<View className='goods-page'>
      {loadingStatus && <Loading/>}
      <GoodsNavbar opacity={opacity}>
        <View className='node-list'>
          {nodeList.map((item, key) => {
            return (<View key={item.id} className={classNames('node-item f-g-5', nodeKey === key && 'node-item__active')} onClick={this.onSwitchNode.bind(this, item, key)}>{item.name}</View>)
          })}
          <View className='under-line' style={{ left: `calc(${nodeKey * percent}% + (${percent}% / 2))` }}/>
        </View>
      </GoodsNavbar>
      <View className='goods-scroll'>
        <View id='goods-info' className='goods-card'>
          <GoodsCarousel images={goodsInfo.images} video={{ url: goodsInfo.video, poster: goodsInfo.videoCoverImg }}/>
          <View className='goods-head'>
            <View className='d-f a-i-c j-c-b'>
              <View className='price d-f a-i-b'>
                <View className='sale-price bnn-number'>
                  <Text className='price-unit'>￥</Text>{goodsInfo.salePrice}
                </View>
                {goodsInfo.originPrice > goodsInfo.salePrice && <View className='origin-price bnn-number m-l-10'>￥{goodsInfo.originPrice}</View>}
              </View>
              <View className='user-like f-g-5'>
                <Text className='like-icon bnn-icon m-r-10'>&#xe668;</Text>{goodsInfo.storeCount}人喜欢
              </View>
            </View>
            <View className='goods-name'>{goodsInfo.name}</View>
            <View className='stock-box d-f j-c-b'>
              <View className=''>已兑换{goodsInfo.salesNumber}{goodsInfo.unitName}</View>
              <View className=''>剩余库存{goodsInfo.stockNumber}{goodsInfo.unitName}</View>
            </View>
            {showMemberPrice(goodsInfo) && <View className='member-box d-f a-i-c j-c-b' onClick={() => toMemberOpenPage()}>
              <View className='member-left d-f a-i-c'>
                <Image src={vipImg} className='left-icon'/>
                <View className='left-text'>会员价<Text className='member-price'>￥{goodsInfo.memberPrice}</Text>{goodsInfo.saveMoney ? `省￥${goodsInfo.saveMoney}` : ''}</View>
              </View>
              <View className='member-right d-f a-i-c'>
                <View className='right-text'>{userInfo.isVip ? '' : '立即开通'}</View>
                <View className='right-icon bnn-icon'>&#xe866;</View>
              </View>
            </View>}
            <View className='sales-record d-f j-c-b'>
              <AvatarList list={goodsInfo.salesReport && goodsInfo.salesReport.map(i => i.userInfo && i.userInfo.headImg)} showMore/>
              <View className='invite-btn d-f a-i-c bnn-number' hoverClass='hover-class--btn' onClick={this.setOpenShareImg.bind(this)}>
                {goodsInfo.shareAmount ? `分享赚 ${formatAmount(goodsInfo.shareAmount)} 元` : '分享给好友'}
              </View>
            </View>
            {<View className='tip-list d-f f-w-w'>
              {goodsInfo.tips && goodsInfo.tips.map((str, k) => {
                return (<View key={k} className='tip-item d-f a-i-c'>
                  <View className='bnn-icon tip-icon'>&#xe645;</View>
                  <View className='tip-text l-h-o'>{str}</View>
                </View>)
              })}
            </View>}
          </View>
        </View>

        {/* --------------------------------- 用户评论 --------------------------------- */}
        {commentRes.list && commentRes.list.length && <View id='goods-comment' className='goods-card goods-card__body comment-card'>
          <View className='goods-card__head'>
            <TitleOne>用户评论</TitleOne>
          </View>
          <View className='comment-list'>
            {commentRes.list.map(info => {
              return (<CommentGoods key={info.id} info={info} className='comment-item'/>)
            })}
            <View className='see-more f-g-5' onClick={() => toCommentGoodsPage(goodsInfo.id)}>查看更多好评（{commentRes.totalCount}）</View>
          </View>
        </View>}

        <View className='goods-body'>
          {/* --------------------------------- 商品详情 --------------------------------- */}
          {goodsInfo.description && <View id='goods-desc' className='goods-card'>
            <View className='goods-card__head'>
              <TitleOne>商品详情</TitleOne>
            </View>
            <View className='rich-text-wrap goods-card__body'>
              <RichText nodes={formatHtml(goodsInfo.description)} />
            </View>
          </View>}

          {/* --------------------------------- 购买须知 --------------------------------- */}
          {goodsInfo.buyDescription && <View className='goods-card'>
            <View className='goods-card__head'>
              <TitleOne>购买须知</TitleOne>
            </View>
            <View className='rich-text-wrap goods-card__body'>
              <RichText nodes={formatHtml(goodsInfo.buyDescription)} />
            </View>
          </View>}

          {/* --------------------------------- 商品推荐 --------------------------------- */}
          <View id='goods-hot' className='goods-card'>
            <View className='goods-card__head'>
              <TitleOne>更多美好生活</TitleOne>
            </View>
            <GoodsOneList list={goodsList}/>
          </View>
        </View>
        <View className='goods-foot--height'/>
      </View>

      <GoodsFoot
        menus={['home', 'share', 'cart']}
        onShare={this.setOpenShareImg.bind(this)}>
        {!goodsInfo.disabled && <Button
          className='goods-foot__btns-btn goods-foot__cart-btn xf-btn'
          onClick={this.setState.bind(this, { showSelect: 'cart' })}>加入购物车</Button>}
        <Button
          disabled={goodsInfo.disabled}
          className='goods-foot__btns-btn xf-btn xf-btn-primary'
          onClick={this.setState.bind(this, { showSelect: 'buy' })}>{ goodsInfo.disabledText || '立即购买' }</Button>
      </GoodsFoot>

      <GoodsSelect goods={goodsInfo} isOpened={showSelect} onClose={this.setState.bind(this, { showSelect: false })} onConfirm={this.onConfirm.bind(this, showSelect)}/>
      <ShareImage isOpened={showShareImg} width={500} height={890} image={shareImg} onClose={this.setState.bind(this, { showShareImg: false })}/>
      <BuyRecord/>
    </View>)
  }
}
